package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.cammon.ThreadLocalUtil;
import com.itheima.exception.TokenException;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王同学
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    //拦截器
    @Autowired
    EmployeeMapper employeeMapper;
    //调用Redis
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");  //这个参数是接口文档那边写的
        if (!StringUtils.hasText(token)){
            //如果里面没有内容的话给抛异常,就是没有查到
            throw new TokenException();
        }
        //使用redis
        String employee = (String) redisTemplate.opsForValue().get("employee_token:" + token);
        //调用mapper层的方法 找token
        Employee emp = JSON.parseObject(employee,Employee.class);
        //如果token为空就给他false掉
        if (emp==null){
            throw new TokenException();
        }
        //调用线程
        ThreadLocalUtil.setId(emp.getId());

        return true;
    }

}
